/*!
 @header ProductListViewController.m
 @author 王 文彬
 @version 1.0.0 2013/01/31 Creation
 Copyright (c) 2013年 mypocketbaby. All rights reserved.
 */

#import "ProductListViewController.h"
#import "Helper.h"
#import "Config.h"
#import "ProductFormViewController.h"
#import "JMFBase.h"
#import "ASImageView.h"
#import "SellerServiceViewController.h"
#import "MJRefresh.h"

//  -----------------------类详细介绍-----------------------
//
//  <功能描述>：加载更多
//  	<实现描述>：持有一个BaseRefreshViewController实例替代继承UITableViewController，并且适应BaseRefreshViewControllerDelegate，
//                实现相应的代理方法，通过BaseRefreshViewController的实例变量去控制是否刷新或者是否是下拉刷新或者加载更多。
//  	<注意事项>：PersonalInfoViewController不能以tableview处理，所以就无法继承BaseRefreshViewController。
//                必须适应BaseRefreshViewControllerDelegate,并且持有BaseRefreshViewController一个实例。
//
//  <业务描述>：点击添加按钮时，要判断用户是否已开通卖家服务，如有则push productFormVC，允许用户添加商品；如没有开通卖家服务，则不允许用户添加商品。
//
//  -----------------------类升级日志-----------------------
//
//  修改人   修改时间        修改描述              版本
//
// <#修改人#> <#修改时间#>    <#修改描述#>          <#版本#>

@interface ProductListViewController ()<MJRefreshBaseViewDelegate>

@end

@implementation ProductListViewController
{
    UITableView *_tableView;
    MJRefreshFooterView *_footer;
    MJRefreshHeaderView *_header;
}
//- (id)initWithStyle:(UITableViewStyle)style
//{
//    self = [super initWithStyle:style];
//    if (self) {
//        // Custom initialization
//    }
//    return self;
//}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //背景
    self.view.backgroundColor = [UIColor whiteColor];
    //
    self.title = _L(@"vc_title_062");    //商品管理
    
    _blankPage = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 40.0f, 320.0f, 832.0f/2.0f)];
    
    //导航栏左按钮：返回
    UIButton* backButton = [Helper buttonWithStyle:ButtonStyleNavigationReturn];
    [backButton addTarget:self action:@selector(backButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    //导航按钮右按钮：添加
    UIButton* addButton = [Helper buttonWithStyle:ButtonStyleNavigationAdd];
    [addButton addTarget:self action:@selector(addButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:addButton];
    
    //
    _sellingButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, _SYS_FRAME_WIDTH / 2, 40)];
    _sellingButton.titleLabel.font = _SYS_FONT_004;
    [_sellingButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_sellingButton setTitle:_L(@"btn_product_01") forState:UIControlStateNormal];   //销售中的商品
    [_sellingButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"transaction_bg_001@2x" ofType:@"png"]] forState:UIControlStateNormal];
    [_sellingButton addTarget:self action:@selector(sellingButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_sellingButton];
    
    
    //
    _stopSellingButton = [[UIButton alloc] initWithFrame:CGRectMake(_SYS_FRAME_WIDTH / 2, 0, _SYS_FRAME_WIDTH / 2, 40)];
    _stopSellingButton.titleLabel.font = _SYS_FONT_004;
    [_stopSellingButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_stopSellingButton setTitle:_L(@"btn_product_02") forState:UIControlStateNormal];   //停售中的商品
    [_stopSellingButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"transaction_bg_002@2x" ofType:@"png"]] forState:UIControlStateNormal];
    [_stopSellingButton addTarget:self action:@selector(stopSellingButtonEvent) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_stopSellingButton];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 40, _SYS_FRAME_WIDTH, _SYS_FRAME_HEIGHT-44.0f) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];

    _dataSource = [[NSMutableArray alloc] init];
    
    // 3.3行集成下拉刷新控件
    _header = [MJRefreshHeaderView header];
    _header.scrollView = _tableView;
    _header.delegate = self;
    
    // 4.3行集成上拉加载更多控件
    _footer = [MJRefreshFooterView footer];
    _footer.delegate = self;
    
    // 5.0.5秒后自动下拉刷新
//    [_header performSelector:@selector(beginRefreshing) withObject:nil afterDelay:0.5];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
//    [self loadDataSourceForTableView:_currentStatus byCheckId:nil];
    [_header beginRefreshing];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        
        //图片
        ASImageView* imageView = [[ASImageView alloc] initWithFrame:CGRectMake(10, 5, 25, 25)];
        //        imageView.backgroundColor = [UIColor redColor];
        [cell.contentView addSubview:imageView];
        
        
        //文字
        UILabel* nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, 5, 230, 25)];
        nameLabel.text = @"";
        [cell.contentView addSubview:nameLabel];
        
        
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    
    
    NSDictionary* product = [_dataSource objectAtIndex:indexPath.row];
    NSArray* pictures = [product valueForKey:@"pictures"];
    
    if (![pictures isKindOfClass:[NSNull class]] && pictures.count > 0) {
        [((ASImageView *)[cell.contentView.subviews objectAtIndex:0]) setImageURL:pictures[0][@"previewUrl"] andSourceImageURL:nil forStyle:PictureStyleAvartPreview];
    }
    
    ((UILabel *)[cell.contentView.subviews objectAtIndex:1]).text = [product valueForKey:@"name"];
    
    
    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:true];
    
    if (_productFormVC == nil) {
        _productFormVC = [[ProductFormViewController alloc] init];
    }
    
    [self.navigationController pushViewController:_productFormVC animated:true];
    //由于setProduct方法会从网络读取数据，造成VC载入缓慢，因此把setProduct方法写在push之后
    _productFormVC.product = [_dataSource objectAtIndex:indexPath.row];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    float height = 40;
    
    return height;
}


#pragma mark - 自定义事件

/*!
 @abstract 返回按钮事件
 */
- (void) backButtonEvent
{
    //pop
    [self.navigationController popViewControllerAnimated:true];
}


/*!
 @abstract 正在销售中的商品按钮事件
 */
- (void)sellingButtonEvent
{
    [_sellingButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"transaction_bg_001@2x" ofType:@"png"]] forState:UIControlStateNormal];
    [_stopSellingButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"transaction_bg_002@2x" ofType:@"png"]] forState:UIControlStateNormal];
    [self loadDataSourceForTableView:0 byCheckId:nil];
    _currentStatus = 0;
}

/*!
 @abstract 停止销售的商品按钮事件
 */
- (void)stopSellingButtonEvent
{
    [_sellingButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"transaction_bg_002@2x" ofType:@"png"]] forState:UIControlStateNormal];
    [_stopSellingButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"transaction_bg_001@2x" ofType:@"png"]] forState:UIControlStateNormal];
    [self loadDataSourceForTableView:1 byCheckId:nil];
    _currentStatus = 1;
}

#pragma mark - 私有方法

/*!
 @abstract 根据当前视图的状态，请求正在销售或停止销售的商品列表，并存入_dataSource后绘制tableView
 */
- (void)loadDataSourceForTableView:(int)flag byCheckId:(NSInteger)checkId
{
    JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_PRODUCT_LIST];
    request.delegate = self;
    [request setValue:@(flag) forParameter:@"status"];
    
    //id不为空，说明用户在加载更多
    if(checkId != 0){
        
        [request setValue:@(checkId) forParameter:@"checkId"];
        
        [request setSuccessSelector:@selector(moreProductsDidReceived:)];
    }
    
    [request asynchronous];
}

/*!
 @abstract 获取数据源最后一条数据的id
 @discussion 用于分页功能
 @result 数据源最后一条数据的id
 */
- (NSInteger)catchTheLastDataSourceId
{
    //是0还是_dataSource.count - 1,服务器端问题
    NSInteger lastID = 0;
    if (_dataSource.count > 0) {
        lastID = [[[_dataSource objectAtIndex:(_dataSource.count - 1)] objectForKey:@"id"] integerValue];
    }
    return lastID;
}

#pragma mark - Add Button Process

/*!
 @abstract 保存按钮事件
 */
- (void)addButtonEvent
{
    JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_PRODUCT_SELLER];
    request.hudOn = true;
    request.hudTitle = _L(@"title_loading_06");
    request.delegate = self;
    [request setSuccessSelector:@selector(saveButtonRequestSuccess:)];
    [request setValue:_ACCOUNT_ID forParameter:@"userId"];
    [request asynchronous];
}


- (void)saveButtonRequestSuccess:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        _seller = jmf.data;
        if ([jmf.data[@"sellerType"] intValue] > 0) {
            
            _productFormVC = [[ProductFormViewController alloc] init];
            _productFormVC.product = nil;
            [self.navigationController pushViewController:_productFormVC animated:true];
        }
        //您还不是卖家，请开通卖家服务，再发布商品
        else {
            
            UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:_L(@"alert_83") delegate:self cancelButtonTitle:_L(@"btn_back_02") otherButtonTitles:_L(@"btn_yes_26"), nil];
            [alertView show];
        }
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {

        SellerServiceViewController* sellerServiceViewController = [[SellerServiceViewController alloc] initWithSeller:_seller];
        sellerServiceViewController.dismissMode = true;
        [sellerServiceViewController hasBackButton:true];
        
        UINavigationController* navigationController = [[UINavigationController alloc] initWithRootViewController:sellerServiceViewController];
        [Helper navigationControllerCommonStyle:navigationController];
        
        [self presentModalViewController:navigationController animated:true];
    }
}

//////////////////////////////////////

#pragma mark - JSONRequest Delegate

- (void)requestDidLoadJSON:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        if (_dataSource.count != 0) {
            [_dataSource removeAllObjects];
        }
        
        //将每次下拉刷新出的新数据都加入到数据源的最前面
        if ([(NSArray *)jmf.data count] != 0) {
            
            [_dataSource addObjectsFromArray:(NSArray *)jmf.data];
            
            _footer.scrollView = _tableView;
        }
        
        if (_dataSource.count > 0) {
            _tableView.tableFooterView.hidden = NO;
        }
        else {
            _tableView.tableFooterView.hidden = YES;
        }
        
        [self reloadTableView];
    }
    else {
        
        [Helper easyShowJMFStatus:jmf];
    }

    //数据源为空，那么就设为空页面
    if (_dataSource.count == 0) {
        
        _blankPage.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"transaction_img_006@2x" ofType:@"png"]];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView addSubview:_blankPage];
        
    }else{
        _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        [_blankPage removeFromSuperview];
    }
}

- (void)moreProductsDidReceived:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        if ([(NSArray *)jmf.data count] != 0) {
            _tableView.tableFooterView.hidden = NO;
            [_dataSource addObjectsFromArray:(NSArray *)jmf.data];
            
        }
        else{
            _tableView.tableFooterView.hidden= YES;
        }
        [self reloadTableView];
    }
    else {
        
        [Helper easyShowJMFStatus:jmf];
    }
}

//
- (void)requestFailWithNetworkUnavailabe
{
    [Helper showAlertWithTitle:nil andMessage:_L(@"title_networkunavailabe")];
}

#pragma mark - 刷新的代理方法---进入下拉刷新\上拉加载更多都有可能调用这个方法
- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    //下拉刷新
    if (refreshView == _header) {
        
        //请求初始数据
        [self loadDataSourceForTableView:_currentStatus byCheckId:0];
    }
    
    //上拉加载更多
    else {
        
        if ([self catchTheLastDataSourceId] != 0) {
            [self loadDataSourceForTableView:_currentStatus byCheckId:[self catchTheLastDataSourceId]];
        }
    }
}

//刷新tableview
- (void)reloadTableView
{
    [_tableView reloadData];
    // 结束刷新状态
    [_header endRefreshing];
    [_footer endRefreshing];
}

- (void)dealloc
{
    _dataSource = nil;
}

@end
